import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import {
  Input,
  Badge,
  Button,
  Space,
  Table,
  message,
  Modal,
  Form,
  Select,
  DatePicker,
  Row,
  Col,
  InputNumber
} from 'antd';
import {
  projectList,
  getCompanyList,
  projectAdd,
  projectEdit,
  projectDel,
  projectBack,
} from '@/api/staff';
import './list.css';
import idID from '@/locales/id-ID';

export interface CompanyListItem {
  id: string;
  account: string;
}

export interface ProjectItem {
  id: string;
  title: string;
  companyid: string;
  account: string;
  address: string;
  start_time: string;
  end_time: string;
  gr_security?: number;
  dw_security?: number;
  // 其他可能的字段
}

const { RangePicker } = DatePicker;
const { Option } = Select;

const Welcome: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { Search } = Input;
  const [companyList, setCompanyList] = useState<CompanyListItem[]>([]);
  // 编辑数据
  const [companyEdit, setCompanyEdit] = useState<any>(null);
  // 控制编辑模态框显示隐藏
  const [editModalVisible, setEditModalVisible] = useState(false);

  const [allData, setAllData] = useState<ProjectItem[]>([]);
  const [filteredData, setFilteredData] = useState<ProjectItem[]>([]);
  const [tableData, setTableData] = useState<ProjectItem[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [searchKey, setSearchKey] = useState('');
  // 控制新增模态框显示隐藏
  const [addModalVisible, setAddModalVisible] = useState(false);
  // 表单实例，用于表单操作（重置、验证等）
  const [form] = Form.useForm();
  // 控制回收站模态框显示隐藏
  const [recycleModalVisible, setRecycleModalVisible] = useState(false);
  // 回收站数据
  const [recycleData, setRecycleData] = useState<ProjectItem[]>([]);
  // 回收站当前页、页大小
  const [recycleCurrentPage, setRecycleCurrentPage] = useState(1);
  const [recyclePageSize, setRecyclePageSize] = useState(10);
  // 回收站过滤后数据
  const [filteredRecycleData, setFilteredRecycleData] = useState<ProjectItem[]>([]);
  // 回收站表格当前页数据
  const [recycleTableData, setRecycleTableData] = useState<ProjectItem[]>([]);
  // 回收站数据长度（用于角标）
  const [recycleDataCount, setRecycleDataCount] = useState(0);

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
    },
    {
      title: '公司标识',
      dataIndex: 'companyid',
      align: 'center',
      key: 'companyid',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      align: 'center',
      key: 'account',
    },
    {
      title: '项目地址',
      dataIndex: 'address',
      align: 'center',
      key: 'address',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      align: 'center',
      key: 'start_time',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      align: 'center',
      key: 'end_time',
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (_, record: ProjectItem) => (
        <Space size="middle">
          {/* 点击编辑按钮时传递当前项目的id */}
          <Button type="primary" onClick={() => fetchCompanyEdit(record.id)}>编辑</Button>
          <Button type="primary" danger onClick={() => handleDel(record.id)}>下架</Button>
        </Space>
      ),
    },
  ];

  const recycleColumns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
    },
    {
      title: '公司标识',
      dataIndex: 'companyid',
      align: 'center',
      key: 'companyid',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      align: 'center',
      key: 'account',
    },
    {
      title: '项目地址',
      dataIndex: 'address',
      align: 'center',
      key: 'address',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      align: 'center',
      key: 'start_time',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      align: 'center',
      key: 'end_time',
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (_, record: ProjectItem) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handleRecover(record.id)}>恢复</Button>
        </Space>
      ),
    },
  ];

  const filterDataByTitle = (key: string) => {
    if (!key.trim()) {
      setFilteredData([...allData]);
      return;
    }
    const matchedData = allData.filter((item) =>
      item.title?.toLowerCase().includes(key.toLowerCase())
    );
    setFilteredData(matchedData);
    setCurrentPage(1);
  };

  const sliceCurrentPageData = (page: number = currentPage, size: number = pageSize) => {
    if (filteredData.length === 0) {
      setTableData([]);
      return;
    }
    const startIndex = (page - 1) * size;
    const endIndex = startIndex + size;
    const currentPageData = filteredData.slice(startIndex, endIndex);
    setTableData(currentPageData);
  };

  const handleSearch = (value: string) => {
    setSearchKey(value);
    filterDataByTitle(value);
  };

  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    sliceCurrentPageData(page, size);
  };

  const fetchCompanyList = async () => {
    try {
      const res: any = await getCompanyList({});
      if (res && res.data) {
        setCompanyList(res.companylist || []);
        console.log('公司列表', res.companylist);
      }
    } catch (error) {
      console.error('获取公司列表失败:', error);
      message.error('获取公司列表失败');
    }
  };

  // 编辑回显 - 接收项目id作为参数
  const fetchCompanyEdit = async (id: string) => {
    try {
      // 将获取到的id传递给编辑接口
      console.log('项目id', id);

      const res: any = await projectEdit({ id: id });
      if (res.code === 1) {
        setCompanyEdit(res.data);
        console.log('编辑数据', res.data);
        // 打开编辑模态框
        setEditModalVisible(true);
        // 回显表单数据（日期转换为 dayjs 对象）
        form.setFieldsValue({
          projectCompany: res.data.companyid,
          title: res.data.title,
          address: res.data.address,
          projectPeriod: [
            res.data.start_time ? dayjs(res.data.start_time) : null,
            res.data.end_time ? dayjs(res.data.end_time) : null
          ],
          personalSocialSecurityBase: res.data.gr_security || 0,
          unitSocialSecurityBase: res.data.dw_security || 0,
          // 回显账号信息（根据接口返回的account结构调整）
          operatorAccount: res.account?.[0]?.account || '',
          accountantAccount: res.account?.[1]?.account || '',
          managerAccount: res.account?.[2]?.account || '',
        });
      }
    } catch (error) {
      console.error('获取编辑数据失败:', error);
      message.error('获取编辑数据失败');
    }
  };

  // 请求回收站项目列表
  const fetchRecycleList = async () => {
    try {
      const res = await projectList({ status: 1 });
      const fullData = res.data || [];
      setRecycleData(fullData);
      setFilteredRecycleData(fullData);
      // 同步更新回收站数据长度（角标）
      setRecycleDataCount(fullData.length);
    } catch (error) {
      console.error('请求回收站列表失败：', error);
      message.error('请求回收站列表失败');
      setRecycleDataCount(0); // 错误时角标置为 0
    }
  };

  // 切分回收站当前页数据
  const sliceRecycleCurrentPageData = (
    page: number = recycleCurrentPage,
    size: number = recyclePageSize
  ) => {
    if (filteredRecycleData.length === 0) {
      setRecycleTableData([]);
      return;
    }
    const startIndex = (page - 1) * size;
    const endIndex = startIndex + size;
    const currentPageData = filteredRecycleData.slice(startIndex, endIndex);
    setRecycleTableData(currentPageData);
  };
  // 回收站搜索
  const handleRecycleSearch = (value: string) => {
    if (!value.trim()) {
      setFilteredRecycleData([...recycleData]);
      return;
    }
    const matchedData = recycleData.filter((item) =>
      item.title?.toLowerCase().includes(value.toLowerCase())
    );
    setFilteredRecycleData(matchedData);
    setRecycleCurrentPage(1);
  };

  // 回收站分页变化
  const handleRecyclePageChange = (page: number, size: number) => {
    setRecycleCurrentPage(page);
    setRecyclePageSize(size);
    sliceRecycleCurrentPageData(page, size);
  };
  // 处理下架操作
  const handleDel = async (id: string) => {
    // 假设账户 id 为 1 禁止下架，这里先判断项目 id（若实际是账户 id，需调整判断逻辑）
    if (id === '1') {
      message.warning('账户 id 为 1，禁止下架');
      return;
    }
    try {
      const res = await projectDel({ id });
      if (res.code === 1) {
        message.success('下架成功');
        // 重新请求项目列表，更新表格数据
        fetchRecycleList();
        projectList({ status: 0 }).then((listRes) => {
          const newFullData = listRes.data || [];
          setAllData(newFullData);
          setFilteredData(newFullData);
          sliceCurrentPageData();
        });
      } else {
        message.error(res.msg || '下架失败');
      }
    } catch (error) {
      console.error('下架失败：', error);
      message.error('下架失败');
    }
  };
  // 恢复项目
  const handleRecover = async (id: string) => {
    try {
      const res = await projectBack({ id });
      if (res.code === 1) {
        message.success('恢复成功');
        // 重新请求回收站和正常项目列表
        fetchRecycleList();
        projectList({ status: 0 }).then((listRes) => {
          const newFullData = listRes.data || [];
          setAllData(newFullData);
          setFilteredData(newFullData);
          sliceCurrentPageData();
        });
      } else {
        message.error(res.msg || '恢复失败');
      }
    } catch (error) {
      console.error('恢复失败：', error);
      message.error('恢复失败');
    }
  };
  useEffect(() => {
    sliceRecycleCurrentPageData(recycleCurrentPage, recyclePageSize);
  }, [filteredRecycleData, recycleCurrentPage, recyclePageSize]);
  useEffect(() => {
    projectList({ status: 0 }).then((res) => {
      const fullData = res.data || [];
      setAllData(fullData);
      setFilteredData(fullData);
      sliceCurrentPageData();
    }).catch((err) => {
      console.error('请求项目列表失败：', err);
      setAllData([]);
      setFilteredData([]);
    });
    fetchCompanyList();
    fetchRecycleList();
  }, []);

  useEffect(() => {
    sliceCurrentPageData(currentPage, pageSize);
  }, [filteredData, currentPage, pageSize]);

  // 打开新增模态框
  const showAddModal = () => {
    setAddModalVisible(true);
    form.resetFields(); // 重置表单
  };

  // 关闭新增模态框
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
    form.resetFields();
  };

  // 关闭编辑模态框
  const handleEditModalCancel = () => {
    setEditModalVisible(false);
    form.resetFields();
  };

  // 提交表单（新增和编辑通用）
  const handleFormSubmit = () => {
    form.validateFields().then((values) => {
      // 处理时间范围
      const [startTime, endTime] = values.projectPeriod;

      // 构建请求参数
      const projectData: any = {
        companyid: values.projectCompany,
        title: values.title,
        address: values.address,
        start_time: startTime.format('YYYY-MM-DD'),
        end_time: endTime.format('YYYY-MM-DD'),
        gr_security: values.personalSocialSecurityBase,
        dw_security: values.unitSocialSecurityBase,
        account: [values.operatorAccount, values.accountantAccount, values.managerAccount],
        password: [values.operatorPassword, values.accountantPassword, values.managerPassword],
        project_type: [1, 2, 3],
      };

      // 编辑时添加 projectid
      if (companyEdit && companyEdit.id) {
        projectData.projectid = companyEdit.id;
      }

      projectAdd(projectData)
        .then((res) => {
          if (res.code === 1) {
            console.log(projectData);
            message.success(companyEdit ? '编辑项目成功' : '新增项目成功');
            // 重新请求数据
            projectList({ status: 0 }).then((listRes) => {
              const newFullData = listRes.data || [];
              setAllData(newFullData);
              setFilteredData(newFullData);
              sliceCurrentPageData();
              // 关闭对应的模态框
              if (companyEdit) {
                setEditModalVisible(false);
                setCompanyEdit(null);
              } else {
                setAddModalVisible(false);
              }
              form.resetFields();
            });
          } else {
            console.log(projectData);
            message.error(res.msg || (companyEdit ? '编辑项目失败' : '新增项目失败'));
          }
        })
        .catch((err) => {
          console.error(`${companyEdit ? '编辑' : '新增'}项目失败：`, err);
          message.error(`${companyEdit ? '编辑' : '新增'}项目失败`);
        });
    }).catch((err) => {
      console.error('表单验证失败：', err);
    });
  };

  return (
    <PageContainer style={{ backgroundColor: 'white' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Search
          placeholder="请输入项目名称"
          value={searchKey}
          onChange={(e) => setSearchKey(e.target.value)}
          onSearch={handleSearch}
          style={{ width: 220 }}
        />
        <div style={{ display: 'flex', gap: '20px' }}>
          <Badge count={recycleDataCount}>
            <Button type="primary" danger onClick={() => setRecycleModalVisible(true)}>
              回收站
            </Button>
          </Badge>
          <Button type="primary" onClick={showAddModal}>
            新增
          </Button>
        </div>
      </div>
      {/* 正常项目表格 */}
      <Table
        columns={columns}
        dataSource={tableData}
        bordered
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: filteredData.length,
          onChange: handlePageChange,
          showSizeChanger: true,
          pageSizeOptions: ['5', '10', '50', '100'],
          showTotal: (total) => `共 ${total} 条数据`,
          locale: { emptyText: '暂无匹配的项目数据' },
        }}
        locale={{ emptyText: '暂无项目数据' }}
      />

      {/* 回收站模态框 */}
      <Modal
        title="回收站"
        open={recycleModalVisible}
        onCancel={() => setRecycleModalVisible(false)}
        width={1200}
        footer={null}
      >
        <div style={{ marginBottom: 16 }}>
          <Search
            placeholder="请输入项目名称搜索回收站项目"
            onSearch={handleRecycleSearch}
            style={{ width: 220 }}
          />
        </div>
        <Table
          columns={recycleColumns}
          dataSource={recycleTableData}
          bordered
          pagination={{
            current: recycleCurrentPage,
            pageSize: recyclePageSize,
            total: filteredRecycleData.length,
            onChange: handleRecyclePageChange,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '50', '100'],
            showTotal: (total) => `共 ${total} 条数据`,
            locale: { emptyText: '暂无匹配的回收站数据' },
          }}
          locale={{ emptyText: '回收站暂无数据' }}
        />
      </Modal>

      {/* 新增、编辑项目模态框（保持原有） */}
      <Modal
        title="新增项目"
        open={addModalVisible}
        onCancel={handleAddModalCancel}
        onOk={handleFormSubmit}
        width={1200}
      >
        <Form form={form} layout="vertical">
          {renderFormContent()}
        </Form>
      </Modal>

      <Modal
        title="编辑项目"
        open={editModalVisible}
        onCancel={handleEditModalCancel}
        onOk={handleFormSubmit}
        width={1200}
      >
        <Form form={form} layout="vertical">
          {renderFormContent()}
        </Form>
      </Modal>
    </PageContainer>
  );

  // 提取表单内容为公共函数
  function renderFormContent() {
    return (
      <>
        <Form.Item
          name="projectCompany"
          label="项目所属公司"
          layout="horizontal"
          labelCol={{ span: 3 }}
          rules={[{ required: true, message: '请选择项目所属公司' }]}
        >
          <Select placeholder="请选择项目所属公司">
            {companyList.map((company) => (
              <Option key={company.id} value={company.id}>
                {company.account}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="title"
          label="项目名称"
          layout="horizontal"
          labelCol={{ span: 3 }}
          rules={[{ required: true, message: '请输入项目名称' }]}
        >
          <Input placeholder="请输入项目名称,例:人力资源项目-A" />
        </Form.Item>
        <Form.Item
          name="address"
          label="项目地址"
          layout="horizontal"
          labelCol={{ span: 3 }}
          rules={[{ required: true, message: '请输入项目地址' }]}
        >
          <Input placeholder="请输入项目地址" />
        </Form.Item>
        <Form.Item
          name="projectPeriod"
          label="项目周期"
          layout="horizontal"
          labelCol={{ span: 3 }}
          rules={[{ required: true, message: '请选择项目周期' }]}
        >
          <RangePicker format="YYYY-MM-DD" />
        </Form.Item>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="operatorAccount"
              label="操作员账号"
              layout="horizontal"
              labelCol={{ span: 6 }}
              rules={[{ required: true, message: '请输入操作员账号' }]}
            >
              <Input placeholder="请输入操作员账号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="operatorPassword"
              label="操作员密码"
              layout="horizontal"
              labelCol={{ span: 6 }}
              rules={[{ required: true, message: '请输入操作员密码' }]}
            >
              <Input.Password placeholder="请输入操作员密码" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="accountantAccount"
              label="项目会计账号"
              layout="horizontal"
              labelCol={{ span: 6 }}
              rules={[{ required: true, message: '请输入项目会计账号' }]}
            >
              <Input placeholder="请输入项目会计账号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="accountantPassword"
              label="项目会计密码"
              layout="horizontal"
              labelCol={{ span: 6 }}
              rules={[{ required: true, message: '请输入项目会计密码' }]}
            >
              <Input.Password placeholder="请输入项目会计密码" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="managerAccount"
              label="项目经理账号"
              layout="horizontal"
              labelCol={{ span: 6 }}
              rules={[{ required: true, message: '请输入项目经理账号' }]}
            >
              <Input placeholder="请输入项目经理账号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="managerPassword"
              label="项目经理密码"
              layout="horizontal"
              labelCol={{ span: 6 }}
              rules={[{ required: true, message: '请输入项目经理密码' }]}
            >
              <Input.Password placeholder="请输入项目经理密码" />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          name="personalSocialSecurityBase"
          label="个人社保基数"
          layout="horizontal"
          labelCol={{ span: 3 }}
        >
         <InputNumber min={1} placeholder='请输入个人社保基数' style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          name="unitSocialSecurityBase"
          label="单位社保基数"
          layout="horizontal"
          labelCol={{ span: 3 }}
        >
          <InputNumber min={1} placeholder='请输入单位社保基数' style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="projectIntroduction" label="项目介绍" layout="horizontal" labelCol={{ span: 3 }} >
          <Input.TextArea rows={4} placeholder="请输入项目介绍" />
        </Form.Item>
      </>
    );
  }
};

export default Welcome;
